package com.qdu.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.qdu.entity.Userinfo;
import com.qdu.entity.Validate;
import com.qdu.service.UserService;
import com.qdu.service.ValidateService;
import com.qdu.util.GenerateUUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    private  ValidateService validateService;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    Userinfo user;

    @GetMapping("/getbyuid")
    public Userinfo selectByPrimaryKey(String uid){
        return userService.selectByPrimaryKey(uid);
    }

    @PostMapping("/delete")
    public void deleteByPrimaryKey(String uid){
        userService.deleteByPrimaryKey(uid);
    }

//    @PostMapping("/insert")
//    public void insert(Userinfo userinfo){
//        userService.insert(userinfo);
//    }

//    @PostMapping("/update")
//    public void updateByPrimaryKeySelective(Userinfo userinfo,Model model){
//        userService.updateByPrimaryKeySelective(userinfo);
//    }

    @PostMapping("/updateselective")
    public void updateByPrimaryKeySelective(Userinfo record){
        userService.updateByPrimaryKeySelective(record);
    }

    @PostMapping("/registation")                      //@RequestBody与HttpServletRequest冲突
    @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
    public Result UserRegistation(Userinfo user,@RequestParam("file") MultipartFile file, HttpServletRequest req) throws FileNotFoundException, UnknownHostException {
        System.out.println(user);
//        System.out.println(file.getOriginalFilename());

        Result result=new Result();
        Map<String,Object> results = new HashMap<>();
        if(userService.selectByUname(user.getUname())!=null){
            result.setStatus(false);
            result.setMsg("该用户名已经被注册过了！");
//            results.put("result",result);
        }else if(userService.selectByUphone(user.getUphone())!=null){
            result.setStatus(false);
            result.setMsg("该手机号已经被注册过了！");
//            results.put("result",result);
        }else if(userService.selectByUemail(user.getUemail())!=null){
            result.setStatus(false);
            result.setMsg("邮箱已经被注册了！");
        }else{
            String uid = "U" + GenerateUUID.generateUUID();
            user.setUid(uid);
            SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
            String originName = file.getOriginalFilename();
//            System.out.println(originName);


            String format = sdf.format(new Date());
//            String realPath = "src/main/resources/static";
//            String realPath = ResourceUtils.getURL("classpath:static").getPath();
//            String realPath = System.getProperty("user.dir")+"/src/main/resources/static";
//            String realPath= ResourceUtils.getURL("classpath:static/img").getPath();
//            String realPath = req.getServletContext().getRealPath("/") + format;
            String realPath = req.getServletContext().getRealPath("/") + format;
            System.out.println(realPath);
            String newName = UUID.randomUUID().toString() + ".jpg";

            File folder = new File(realPath);
            if(!folder.exists()){
                folder.mkdirs();
            }
            try {
                file.transferTo(new File(folder, newName));
                String url = req.getScheme() + "://" + InetAddress.getLocalHost().getHostAddress() + ":" + req.getServerPort() + req.getContextPath() + format + newName;
                user.setUimg(url);
                user.setUpwd(encoder.encode(user.getUpwd()));
                userService.insert(user);
                System.out.println(url);

                results.put("status", "success");
//                results.put("url", url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            result.setStatus(true);
            result.setMsg("用户注册成功！");
        }
        return result;
    }

    @PostMapping("/updateusermessage")
    public Result UpdateUserMessage(Userinfo userinfo,MultipartFile file,HttpServletRequest req){
        Result result=new Result();

        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String originName = file.getOriginalFilename();
        System.out.println(originName);

        String format = sdf.format(new Date());

        String realPath = req.getServletContext().getRealPath("/") + format;

        File folder = new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String newName = UUID.randomUUID().toString() + ".jpg";
        try {
            file.transferTo(new File(folder, newName));
            String url = req.getScheme() + "://" + InetAddress.getLocalHost().getHostAddress() + ":" + req.getServerPort() + req.getContextPath() + format + newName;
//            user.setUpwd(encoder.encode(user.getUpwd()));
//            userService.insert(user);
            System.out.println(url);
            userinfo.setUimg(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

//        userinfo.setUpwd(encoder.encode(userinfo.getUpwd()));
        userService.updateByPrimaryKey(userinfo);
        result.setStatus(true);
        result.setMsg("用户信息修改成功！");
        return result;
    }

    @PostMapping("/upload")
    public Map<String, Object> fileupload(String uid,MultipartFile file, HttpServletRequest req){
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        Map<String,Object> result = new HashMap<>();
        String originName = file.getOriginalFilename();
        System.out.println(originName);

        //在开发测试模式时，得到地址为：{项目跟目录}/target/static/images/upload/
        //在打成jar正式发布时，得到的地址为:{发布jar包目录}/static/images/upload/
        String path= ClassUtils.getDefaultClassLoader().getResource("static/img").getPath();
        System.out.println("------------------------------------------------"+path);


//        String format = sdf.format(new Date());
//
//        String realPath = req.getServletContext().getRealPath("/") + format;
//        System.out.println(realPath);

//        File folder = new File(realPath);
        File folder = new File(path);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String newName = UUID.randomUUID().toString() + ".jpg";
        try {
            file.transferTo(new File(folder, newName));
//            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() +"/lease_house"+ format + newName;

            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() +"/lease_house"+ newName;
            System.out.println(url);
            Userinfo user=userService.selectByPrimaryKey(uid);
            user.setUimg(url);
            userService.updateByPrimaryKey(user);
            System.out.println(url);

            result.put("status", "success");
            result.put("url", url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping("/login")
    public Map UserLogin(@RequestBody Map<String,String> params){
//        Result result=new Result();
        HashMap<String, Object> response = new HashMap<>();
        HashMap<String, Object> responseData = new HashMap<>();

        user = userService.selectByUemail(params.get("uemail"));
        System.out.println(user);
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        if(user == null){
            // 没有这个管理员
            response.put("code",60000);
            response.put("msg","登录失败，没有这个用户,请查看邮箱输入是否正确");
        }
        else if(bCryptPasswordEncoder.matches(params.get("upwd"),user.getUpwd())){
            responseData.put("token",1);
            response.put("code",20000);
            response.put("msg","登录成功");
            response.put("data",responseData);
            System.out.println(response);
        }else {
            // 密码错误
            response.put("code",60204);
            response.put("msg","登录失败，密码错误");
        }

        return response;
    }

    @PostMapping("/loginout")
    public Result loginOut(HttpSession session){
        Result result=new Result();
        session.invalidate();
        result.setMsg("用户已退出！");
        result.setStatus(true);
        return result;
    }

    @GetMapping("/info")
    public Map info() {
        HashMap<String, Object> responseInfo = new HashMap<>();
        HashMap<String, Object> responseData = new HashMap<>();
        HashMap<String, Object> userinfo = new HashMap<>();

        userinfo.put("uid",user.getUid());
        userinfo.put("uname",user.getUname());
        userinfo.put("ubirthday",user.getUbirthday());
        userinfo.put("uemail",user.getUemail());
        userinfo.put("ugender",user.getUgender());
        userinfo.put("uphone",user.getUphone());
        userinfo.put("upwd",user.getUpwd());
        userinfo.put("uimg", user.getUimg());

        responseData.put("user", userinfo);
        responseData.put("token",1);

        responseInfo.put("code",20000);
        responseInfo.put("msg","登录成功");
        responseInfo.put("data",responseData);
        return responseInfo;
    }

    Validate validate;

    @PostMapping("/sendemail")
    public Result findPassword(@RequestBody Map param,HttpServletRequest request) throws MessagingException, UnsupportedEncodingException {
        Result result=new Result();
        String uemail = param.get("uemail").toString();
        System.out.println(uemail);
        Userinfo userinfo=userService.selectByUemail(uemail);

        if(userinfo==null){
            result.setStatus(false);
            result.setMsg("邮箱未被注册");
        }else{
            if(validateService.sendValidateLimitation(uemail,10)) {
                validate = new Validate();
                validateService.insertNewResetRecord(validate, userinfo, UUID.randomUUID().toString());
//                String appUrl = request.getScheme() + "://" + request.getServerName()+":"+request.getServerPort();

                String appUrl = "http://localhost:8080/#/rebackpwd2";
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
                mimeMessageHelper.setTo(userinfo.getUemail());
                mimeMessageHelper.setFrom(from,"泊寓（青岛）");
                mimeMessageHelper.setSubject("重置密码");
                StringBuilder sb = new StringBuilder();
                sb.append("<html><head></head>");

//                        "<a href = "+appUrl +"/lease_house/users/findpassword?token="+validate.getVtoken()+">"+appUrl +"/validate/toFindPassword?token=" +validate.getVtoken()+"</a></body>");
//                "<a href = "+appUrl+">"+"重置密码"+"</a></body>");
                sb.append("<body><h1>恭喜您修改密码成功，已经可以登录了！</h1>");
                sb.append("</html>");
                mimeMessageHelper.setText(sb.toString(), true);
                validateService.sendPasswordResetEmail(mimeMessage);
            }else {
                result.setStatus(false);
                result.setMsg("操作过于频繁，请稍后再试！");
            }
        }
        return result;
    }



    @PostMapping("/restpassword")
    public Result restPassword(@RequestBody Map map){
        String newPassword = map.get("pass").toString();
        Result result=new Result();
//        Validate validate=validateService.findUserByResetToken(vtoken);
        if(validateService.validateLimitation(validate.getUemail(),1,validate.getVtoken())){
            Userinfo userinfo=userService.selectByUemail(validate.getUemail());
            userinfo.setUpwd(encoder.encode(newPassword));
            userService.updateByPrimaryKey(userinfo);
            result.setStatus(true);
            result.setMsg("密码重置成功！");
        }else{
            result.setStatus(false);
            result.setMsg("此邮件已经失效！");
        }
        return result;
    }
}
